package StudyCode.summary.myfile;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class FileEncoding {
	public static String getTextTransferEncoding(InputStream content)
			throws IOException {

		BufferedInputStream in = new BufferedInputStream(content, 4096);

		int span = 0;
		boolean containsLongLines = false;
		int asciiChars = 0;
		int nonAsciiChars = 0;

		while (true) {
			int ch = in.read();
			if (ch == -1) {
				break;
			}

			if (ch == '\n' || ch == '\r') {
				span = 0;
			} else {
				span++;
				if (span > 998) {
					containsLongLines = true;
				}

				if (!isAscii(ch)) {
					nonAsciiChars++;
				} else {
					asciiChars++;
				}
			}
		}

		if (nonAsciiChars == 0) {
			if (containsLongLines) {
				return "quoted-printable";
			} else {
				return "7bit";
			}
		} else {
			if (nonAsciiChars > asciiChars) {
				return "base64";
			} else {
				return "quoted-printable";
			}
		}
	}


	public static String getTextTransferEncoding(String content) {

		int asciiChars = 0;
		int nonAsciiChars = 0;

		for (int i = 0; i < content.length(); i++) {
			int ch = content.charAt(i);

			if (!isAscii(ch)) {
				nonAsciiChars++;
			} else {
				asciiChars++;
			}
		}

		if (nonAsciiChars == 0) {
			return "7bit";
		} else {
			if (nonAsciiChars > asciiChars) {
				return "base64";
			} else {
				return "quoted-printable";
			}
		}
	}


	public static boolean isAscii(String s) {
		for (int i = 0; i < s.length(); i++) {
			if (!isAscii(s.charAt(i))) {
				return false;
			}
		}
		return true;
	}


	private static boolean isAscii(int ch) {
		if (ch == '\r' || ch == '\n' || ch == '\t') {
			return true;
		}

		return ch < 127 && ch >= 32;
	}
}
